package com.one.controller;

import com.one.common.Result;
import com.one.mapper.UserMapper;
import com.one.pojo.User;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;

/**
 * 用户 控制层 路由
 */

@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    UserMapper userMapper;

    @PostMapping("/save")
    public Result<?> save(@RequestBody User user) {  //?表示任何类型 //RequestBody把json转换成java对象
        /**
         * 添加用户数据
         */
        if (user.getPassword() == null){// 默认密码为123456
            user.setPassword("123456");
        }
        userMapper.add(user);
        return Result.success();
    }

    @PutMapping("/update")
    public Result<?> update(@RequestBody User user) {
        /**
         * 更新用户数据
         */
        userMapper.updateById(user);
        return Result.success();
    }

    @GetMapping("/limit")
    public Result<?> limit(@RequestParam(defaultValue = "1") int startIndex,
                           @RequestParam(defaultValue = "10") int pageSize) {
        /**
         * 分页查询
         */
        HashMap<String,Integer> map = new HashMap<String,Integer>();
        if (startIndex == 1) {
            map.put("startIndex",startIndex-1);
        }else {
            map.put("startIndex",(startIndex-1)*pageSize);//分页逻辑
        }
        map.put("pageSize",pageSize);
        List<User> limit = userMapper.limit(map);
        return Result.success(limit);
    }

    @GetMapping("/search")
    public Result<?> search(@RequestParam(defaultValue = "") String name) {
        /**
         * 根据用户名 关键字 搜索 对象数据
         */
        String name_pinjie = "%"+name+"%"; //模糊查询  拼接 %
        List<User> search_result = userMapper.search(name_pinjie);
        return Result.success(search_result);
    }

    @GetMapping("/select")
    public Result<?> select() {
        /**
         * 查询总数居 条数
         */
        return Result.success(userMapper.select());
    }

    @DeleteMapping("/delete/{id}")
    public Result<?> deleteById(@PathVariable int id) {
        /**
         * 根据id 删除 数据
         */
        userMapper.deleteById(id);
        return Result.success();
    }

    @PostMapping("/login")
    public Result<?> login(@RequestBody User user) {
        /**
         * 用户登录 通过用户名 查用户数据
         */
        User res = userMapper.login(user.getName());
        if (res == null) {
            return Result.error("400","用户名不存在");
        }else if (user.getPassword().equals(res.getPassword())) {
            return Result.success(user.getName());
        }else
            return Result.error("400","用户名、密码不匹配");
    }

}
